import { Checkbox, Modal, Tree } from "antd";
import { useCallback, useEffect, useState } from "react";
import { request } from "../../../Api/api";

const GiveRight = ({
  id,
  open = false,
  onOk = () => {},
  onCancel = () => {},
}) => {
  const [rightTrees, setRightTrees] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [expandedKeys, setExpandedKeys] = useState([]);
  const getAllKeys = useCallback((treeData) => {
    let keys = [];
    treeData.forEach((item) => {
      keys.push(item.id);
      if (item.children) {
        keys = keys.concat(getAllKeys(item.children));
      }
    });
    return keys;
  }, []);
  useEffect(() => {
    if (open) {
      setCheckedKeys([]);
      async function fetchData() {
        // 获取权限树
        const res = await request("/right/tree", {}, "GET");
        setRightTrees(res.data);
        setExpandedKeys(getAllKeys(res.data));
        // 获取 用户已有权限
        const res2 = await request("/user/right", { id }, "GET");
        setCheckedKeys(res2.data);
      }
      fetchData();
    }
  }, [id, open, getAllKeys]);
  return (
    <Modal
      centered
      open={open}
      onOk={() => {
        onOk(checkedKeys);
      }}
      onCancel={onCancel}
      okText="授权"
      cancelText="取消"
    >
      <Checkbox
        onChange={(e) => {
          if (e.target.checked) {
            setCheckedKeys(getAllKeys(rightTrees));
          } else {
            setCheckedKeys([]);
          }
        }}
      >
        全选
      </Checkbox>
      <div style={{ height: "80vh", overflow: "auto" }}>
        <Tree
          showLine
          blockNode
          treeData={rightTrees}
          expandedKeys={expandedKeys}
          onExpand={(keys) => {
            setExpandedKeys(keys);
          }}
          checkedKeys={checkedKeys}
          checkStrictly
          onCheck={(checkedKeys) => {
            setCheckedKeys(checkedKeys.checked);
          }}
          checkable
          fieldNames={{ title: "name", key: "id", children: "children" }}
        />
      </div>
    </Modal>
  );
};
export default GiveRight;
